package com.siecom.module;

import android.os.Bundle;
import android.util.Log;

import com.siecom.constconfig.ErrorDefine;
import com.siecom.tool.ByteTool;
import com.siecom.tool.Timer;

import java.io.IOException;

/**
 * Created by ghkjg on 2017/5/2.
 */

public class KeyInputRunnable extends ModuleRunnable {
    private final static String TAG = "KeyInputRunnable";
    public static CipherKeyBoardModule keyBoardModule = CipherKeyBoardModule.getInstance();

    private byte[] RecvBuff = new byte[2176];
    private int[] RecvLen = new int[1];
    private int keyTimeOut;

    public KeyInputRunnable(DeviceCallback callback, boolean isOnMain, int timeOut) {

        keyTimeOut = timeOut;
        this.callback = callback;
        this.isOnMain = isOnMain;
    }

    public void stopRun() {
        this.runFlag = false;
        keyBoardModule.setStopRun(true);
    }


    private byte[] rspmsg = new byte[1];

    @Override
    public void run() {
        //设置使用的密钥
        synchronized (this) {

            int ret = keyBoardModule.setEncryptMode(CipherKeyBoardModule.WORK_KEY_P, DeviceInterface.SM4_MODE);
            ret = keyBoardModule.useTwoComponent();
            if (ret != 0) {
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                return;
            }

            deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);

            ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
            String hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
            byte[] by = ByteTool.hexStr2Bytes(hexStr);
            ret = by[1];
            Log.e("ret1", ByteTool.byte2hex(by) + "=====");
            if (ret != (byte) 0x84) {
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                return;
            }

            try {
                //管理员1的密码
                ret = recvInput(6);

                if (ret != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
                hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
                by = ByteTool.hexStr2Bytes(hexStr);
                ret = by[1];
                Log.e("ret2", ret + "=====");
                if (ret != (byte) 0x85) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                //管理员2的密码
                ret = recvInput(6);
                if (ret != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
                hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
                by = ByteTool.hexStr2Bytes(hexStr);
                ret = by[1];
                Log.e("ret3", ret + "=====");
                if (ret != (byte) 0x97) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                // 输入分量1
                ret = recvInput(32);
                ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
                hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
                by = ByteTool.hexStr2Bytes(hexStr);
                ret = by[1];
                Log.e("ret3", ret + "=====");
                if (ret != (byte) 0x98) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                //输入分量2
                ret = recvInput(32);
                ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
                hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
                by = ByteTool.hexStr2Bytes(hexStr);
                ret = by[1];
                Log.e("ret3", ret + "=====");
                if (ret != (byte) 0x99) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }
                // 输入校验值
                ret = recvInput(6);

                ret = keyBoardModule.RecvPacket(RecvBuff, RecvLen, 500);
                hexStr = new String(RecvBuff, 0, RecvLen[0]).trim();
                by = ByteTool.hexStr2Bytes(hexStr);
                ret = by[1];
                Log.e("ret3", ret + "=====");
                if (ret != (byte) 0x04) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.UNKNOW_ERROR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    return;
                }

                Bundle bundle = new Bundle();
                deliverResult(callback, DeviceInterface.Result.COMPLETED, bundle, isOnMain);


            } catch (IOException e) {
                e.printStackTrace();
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.KEY_INPUT_ERR);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_INPUT_ERR));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                return;
            }


        }

    }

    public int recvInput(int length) throws IOException {
        int needInputlength = length;
        Timer timer = new Timer(keyTimeOut);
        timer.start();
        while (runFlag) {
            if (timer.timeOut()) {
                Log.e(TAG, "tm.timeOut!!");
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.KEY_TIME_OUT);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_TIME_OUT));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                keyBoardModule.flush();
                return -8;
            }
            int len = keyBoardModule.receiveBytes(rspmsg, 1, 100);
            if (len == 0) {

                continue;
            }
            if (rspmsg[0] == 0x08) {
                if (needInputlength < length) {
                    needInputlength++;
                    Bundle bundle = new Bundle();
                    bundle.putInt("flag", 0);
                    bundle.putInt("data", length - needInputlength);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                }
            }
            Log.e("pw:" + needInputlength, ByteTool.byte2hex(rspmsg));
            if (rspmsg[0] == 0x02) {
                keyBoardModule.flush();
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.KEY_INPUT_ERR);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.KEY_INPUT_ERR));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                return -1;
            }
            if (rspmsg[0] == 0x1b) {
                //取消输入直接
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.CANCEL_INPUT);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CANCEL_INPUT));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                return -2;
            }
            if (rspmsg[0] == 0x0D) {
                if (needInputlength > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.LENGTH_ERR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.LENGTH_ERR));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                } else {
                    return -3;
                }
            }
            if (rspmsg[0] == 0x2a) {
                Log.e("length:" + needInputlength, ByteTool.byte2hex(rspmsg));
                if (needInputlength > 0) {
                    needInputlength--;
                    Bundle bundle = new Bundle();
                    bundle.putInt("flag", 0);
                    bundle.putInt("data", length - needInputlength);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                }
                Log.e("needInputlength",needInputlength+"===");
                if(needInputlength==0){
                    Bundle bundle = new Bundle();
                    bundle.putInt("flag", 1);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                    return 0;
                }

            }

        }
        return -5;
    }

}
